#include <iostream>
#include <unistd.h>
#include <vector>
#include <string>
#include <pthread.h>
using namespace std;

#define NUM 3

//int *p = nullptr;
__thread int g_val = 0;

class threadData{
public:
    threadData(int number)
    :threadname("thread-"+to_string(number))
    {}
public:
    string threadname;
};

__thread threadData td;

string toHex(pthread_t tid){
    char buffer[128];
    snprintf(buffer, sizeof(buffer), "0x%x", tid);
    return buffer;
}

// 所有线程都会调用这个函数
void *threadRoutine(void *args){
    threadData *td = static_cast<threadData *>(args);
    int i = 0;
    //int test_i = 0;    // 该变量在每个线程的栈区创建

    // if(td->threadname=="thread-2"){
    //     p = &test_i;
    // }

    while (i < 5)
    {
        cout << "pid: " << getpid() << ", tid: " << toHex(pthread_self())
             << ", threadname: " << td->threadname
             << ", g_val: " << g_val << ", &g_val: " << &g_val << endl;
        sleep(1);
        i++;
        //test_i++;
        g_val++;
    }

    delete td;
    return nullptr;
}

int main(){
    // 创建多线程
    vector<pthread_t> tids;
    for (int i = 0; i < NUM; i++){
        pthread_t tid;
        threadData *td = new threadData(i);  // 在堆区创建

        pthread_create(&tid, nullptr, threadRoutine, td);
        tids.push_back(tid);
        sleep(1);
    }

    sleep(1);
    //cout << "main thread get a local value,val: " << *p << ", &val: " << p << endl;
    
    for (int i = 0; i < tids.size(); i++)
    {
        pthread_join(tids[i], nullptr);
    }

    return 0;
}
